package net.joneepenk.util.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

public abstract class JdbcQueryHelper<E> extends JdbcHelper{
	private Logger log = Logger.getLogger(this.getClass());
	public List<E> query(String sql, Object[] params, RowMapper<E> rowMapper){
		LinkedList<E> results = new LinkedList<E>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try{
			conn = getConnection();
			ps = conn.prepareStatement(sql);
			setParams(params, ps);
			long begin = System.nanoTime();
			rs = ps.executeQuery();
			while(rs.next()){
				E obj = rowMapper.map(rs);
				results.add(obj);
			}
			if(log.isDebugEnabled()){
				log.debug("Query spent time: " + (System.nanoTime() - begin));
				log.debug("SELECT SQL Executed: " + ps.toString());
			}
		} catch (SQLException e){
			log.warn("Exception is catched: " + e);
		} finally {
			close(conn, ps, rs);
		}
		return results;
	}

}
